/**
 * 文件下载指令
 * 使用方式 v-download="href"
 * 如果需要指定文件名字使用 v-download="["href", "fileName"]"
 * @Prop fileName 文件名
 * @Prop href 文件地址
 */
import Vue from 'vue'
const fun = (el, binding) => {
  let href = ''
  let fileName = ''
  if (typeof binding.value === 'string') {
    href = binding.value
  } else if (Array.isArray(binding.value)) {
    [href, fileName] = binding.value
  } else {
    console.warn('error params')
    return
  }
  if (!href) {
    console.warn('error url')
    return
  }
  el.onclick = (e) => {
    const modifiers = binding.modifiers
    if (modifiers.prevent) {
      e.preventDefault()
    }
    if (modifiers.stop) {
      e.stopPropagation()
    }
    // console.info(`🔉:使用指令下载文件[${fileName}]`)
    const a: any = document.createElement('a')
    a.href = href
    a.download = fileName || ''
    a.style.opacity = 0
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
  }
}

const downloadDriective = {
  bind: fun,
  update: fun
}

Vue.directive('download', downloadDriective)
